package liwen.zhao.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import liwen.zhao.common.jd.pojo.CommonUser;
import liwen.zhao.common.jd.pojo.Right;
import liwen.zhao.common.jd.pojo.Role;
import liwen.zhao.common.jd.utils.MD5Util;
import liwen.zhao.common.jd.utils.VerifyCode;
import liwen.zhao.common.jd.vo.SysResult;
import liwen.zhao.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Value("${solt}")
    private String solt;
    @Autowired
    UserMapper userMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    ObjectMapper objectMapper=  new ObjectMapper();
    @Override
    public CommonUser findCommonUserByName(String userName) {
        return userMapper.findCommonUserByName(userName,"user/adminLogin");
    }
    
    @Override
    public SysResult adminLogin(String userName, String psw, String action) {
        //密码加盐并md5
        psw= MD5Util.md5(psw+solt);
        CommonUser commonUser;
        
        try{
            commonUser=userMapper.findCommonUserByNameAndPswAndAction(userName,psw,action);
        }catch (Exception e){
            e.printStackTrace();
            return SysResult.build(500,"登录异常",null);
        }
        if(commonUser==null){
            return SysResult.build(500,"用户名或密码错误",null);
        }
        //判断该用户具有后台登录权限
        boolean ifOk=false;
        List<Role> roles=commonUser.getRoles();
        if(null!=roles&&roles.size()>0){
            for(Role role:roles){
                if(ifOk){
                    break;
                }
                List<Right> rights=role.getRightList();
                if(null!=rights&&rights.size()>0){
                    for(Right right:rights){
                        if(1==right.getRight_type()){
                            ifOk=true;
                            break;
                        }
                    }
                }
            }
        }
        if(!ifOk){
            return SysResult.build(500,"无权访问！",null);
        }
        //安全起见，将用户密码值为空
        commonUser.setPsw("");
        String cookieK="cookiek_"+commonUser.getUserName()+System.currentTimeMillis();
        ValueOperations<String, String> stringValueOperations = stringRedisTemplate.opsForValue();
       
        try {
            String commonUserJson=objectMapper.writeValueAsString(commonUser);
            stringValueOperations.set(cookieK,commonUserJson,3, TimeUnit.HOURS);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return SysResult.build(500,"登录异常",null);
        }
      
        
        return SysResult.build(200,"",cookieK);
    }
    
    @Override
    public SysResult getUser(String cookieV) {
        String  commonUserJson=stringRedisTemplate.opsForValue().get(cookieV);
        //超时续租
        expireTime(cookieV);
        CommonUser commonUser=null;
        try {
            commonUser = objectMapper.readValue(commonUserJson,CommonUser.class);
        } catch (IOException e) {
            e.printStackTrace();
            return SysResult.build(500,"登录异常",null);
        }
        if(null==commonUser){
            return SysResult.build(500,"登录异常",null);
        }
        return SysResult.build(200,"",commonUser);
    }
    
    @Override
    public void saveValiCode(String valiCodeId, VerifyCode verifyCode) {
        try {
            stringRedisTemplate.opsForValue().set(valiCodeId,verifyCode.getCode(),20,TimeUnit.MINUTES);
        }catch (Exception e){
            e.printStackTrace();
        }
        
    }
    
    @Override
    public String getValiCode(String valiCodeId) {
        return stringRedisTemplate.opsForValue().get(valiCodeId);
    }
    
    @Override
    public void addUser(CommonUser commonUser) {
        commonUser.setComeFrom("JD");
        commonUser.setRegisterTime(System.currentTimeMillis()/1000);
        userMapper.addCommonUser(commonUser);
    }
    
    @Override
    public CommonUser getCommonUserByUserName(String userName) {
        return  userMapper.getCommonUserByUserName(userName);
    }
    
    @Override
    public String saveFrontUser(CommonUser commonUser) {
        //安全起见，将用户密码值为空
        commonUser.setPsw("");
        String cookieK="front_cookiek_"+commonUser.getUserName()+System.currentTimeMillis();
        ValueOperations<String, String> stringValueOperations = stringRedisTemplate.opsForValue();
    
        try {
            String commonUserJson=objectMapper.writeValueAsString(commonUser);
            stringValueOperations.set(cookieK,commonUserJson,3, TimeUnit.HOURS);
            return cookieK;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public SysResult getCommonUserByCookie(String cookieV) {
       return  getUser(cookieV);
    }
    
    
    //超时续租
    private void expireTime(String cookieV) {
        Long expire = stringRedisTemplate.getExpire(cookieV, TimeUnit.HOURS);
        if(expire>0&&expire<2){
            stringRedisTemplate.expire(cookieV,3,TimeUnit.HOURS);
        }
    }
    
}
